<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item :span="24">
          <!--插入seach组件-->
          <Search :allOpts="formInline.allOpts" v-model="formInline.cOpts" @blur="getAuditTaskHttp"></Search>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleAdd" :disabled="butStatus.add" type="success">创建</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="handleUpdate" :disabled="butStatus.modify">修改</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleDelete" :disabled="butStatus.rm" type="danger">删除</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--列表-->
    <template>
      <el-table v-loading="listLoading"
                :data="tableData"
                border
                style="width: 100%"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="模板名称">
          <template scope="scope">
            <router-link :to="{ path: `page311/${scope.row.user_task_name}`, query: { type: '3' ,taskType:8}}">
              {{scope.row.user_task_name}}
            </router-link>
          </template>
        </el-table-column>
        <el-table-column label="任务类型">
          <template scope="scope">
            {{scope.row.task_run_type | taskRunType}}
          </template>
        </el-table-column>

        <el-table-column prop="user_name"
                         label="用户">
        </el-table-column>
        <el-table-column prop="tenant_name"
                         label="租户">
        </el-table-column>
        <el-table-column prop="create_time"
                         label="创建时间">
        </el-table-column>
        <el-table-column prop="update_time"
                         label="最后更新时间">
        </el-table-column>3
        <el-table-column label="状态">
          <template scope="scope">
            <!-- <span>{{scope.row.task_status | toSta}}</span> -->
            
            <span v-if="scope.row.task_status!='3'">{{scope.row.task_status | toSta}}</span>
            <span v-if="scope.row.task_status=='3'">
              <el-tag :type="scope.row.task_result=='2'?`danger`:`success`">
                {{scope.row.task_result | taskResult}}
              </el-tag>
            </span>

          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template scope="scope">
            <el-button v-if="scope.row.task_run_type == 1" type="primary" size="small"
                       @click="handleChangeState(scope.row)"
                       :disabled="(scope.row.task_status == 1)">启动

            </el-button>
            <el-button v-if="scope.row.task_run_type == 2" :type="scope.row.status=='1'?'primary':'warning'" size="small"
                       @click="handleChangeState(scope.row)">{{scope.row.status | timerBtn}}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!--分页-->
    <el-col :span="24" class="toolbar" style="padding-bottom:10px;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageParm.startIndex"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageParm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageParm.count" style="float:right">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog :title="formTitle" v-model="dialogFormVisible" size="tiny" @close="resetForm">
      <div class="form-warn">
        <el-form :model="form" :rules="editFormRules" ref="form" :label-width="formLabelWidth">
          <el-form-item label="模板名称" prop="user_task_name">
            <el-input v-model="form.user_task_name" :disabled="(dialogFormVisibleType == 'update')?true:false">
            </el-input>
          </el-form-item>
          <el-form-item label="自定义SQL" prop="user_defined_sql">
            <el-input v-model="form.user_defined_sql"
                      type="textarea"
                      :autosize="{ minRows: 4, maxRows: 8}"
                      placeholder="请输入查询SQL">
            </el-input>
          </el-form-item>
          <el-form-item label="租户" prop="tenant_name">
            <el-select v-model="form.tenant_name" placeholder="请选择租户" style="width: 100%;">
              <el-option
                v-for="item in tenantNameList"
                :label="item.tenant_name"
                :value="item.tenant_name">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="提交队列" prop="user_queue_name">
            <el-select v-model="form.user_queue_name" placeholder="请选择" style="width: 100%;" >
              <el-option
                v-for="item in queueOptions"
                :label="item.name"
                :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="触发条件" prop="task_run_type">
            <el-select v-model="form.task_run_type" placeholder="请选择" style="width: 100%;">
              <el-option label="一次执行" value="1"></el-option>
              <el-option label="定时" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.task_run_type == 2" label="Corn表达式" prop="task_timer_cron_exp">
            <el-input v-model="form.task_timer_cron_exp"
                      auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="业务描述"
                        prop="task_desc"
                        :label-width="formLabelWidth">
            <el-input v-model="form.user_task_desc"
                      type="textarea"
                      :autosize="{ minRows:4, maxRows:8}"
                      placeholder="请输入业务描述"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="resetForm">取 消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">{{btnEditText}}</el-button>
      </div>
    </el-dialog>

  </section>
</template>
<script>
  import util from '../../common/util'
  import dao from '../../common/dao'
  import Search from '../../components/Search.vue'
  import NProgress from 'nprogress'
  import UploadPath from '../../components/UploadPath'
  import { mapGetters } from 'vuex'

  export default {
    components: {Search, UploadPath},
    data() {
      return {
        dialogFormVisible: false,
        btnEditText: '提 交',
        formTitle: '创建稽核任务模板',
        editTips: "",
        editLoading: false,
        dialogFormVisibleType: "",
        form: {
          user_task_name: "", //任务名称
          user_defined_sql: "", //任务查询SQL
          user_queue_name: "", //提交队列
          tenant_name: "", //租户名
          task_run_type: "", //任务类型
          cron_exp: "", //定时任务表达式
          user_task_desc: "", //任务描述
        },
        tenantNameList: [], //租户名字数组
        queueOptions: [], //队列
        formLabelWidth: '100px',
        editFormRules: {
          user_task_name: [
            {required: true, message: '请输入任务模板名称', trigger: 'blur'},
            {validator: util.validateString, trigger: 'blur'},
            {validator: this.validateName, trigger: 'blur'}
          ],
          user_defined_sql: [
            {required: true, message: '请输入SQL语句', trigger: 'blur'}
          ],
          tenant_name: [
            {required: true, message: '请选择租户', trigger: 'change'}
          ],
          user_queue_name: [
            {required: true, message: '请输入选择队列', trigger: 'change'}
          ],
          task_timer_cron_exp: [
            {required: true, message: '请输入Cron表达式', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                if (value == '') { callback() }
                else {
                  try {
                    dao.cronValid({task_timer_cron_exp:value}).then(res=>{
                      if(res.FX.err){
                        callback(new Error('服务有误'))
                        return false;
                      }
                      if(res.body.isCronValid==1){
                        callback(new Error('表达式有误'));
                      }else {
                        callback();
                      }
                    })
                  } catch (err){
                    console.log('Error: ' + err.message);
                    callback(new Error('表达式有误'));
                  }
                }
              }, trigger: 'blur'
            }
          ],
          task_run_type: [
            {required: true, message: '请选择选择触发条件', trigger: 'change'}
          ]
        },
        butStatus: {
          modify: true,
          deploy: true,
          add: false,
          rm: true
        },
        multipleSelection: [],
        formInline: {
          allOpts: [{
            key: 'user_task_name',
            label: '模板名称',
            type: '',
            val: ''
          }, {
            key: 'user_name',
            label: '用户',
            type: '',
            val: ''
          }, {
            key: 'task_run_type',
            label: '任务类型',
            type: 'sel',
            selOption: [{
              label: "一次性任务",
              value: "1"
            }, {
              label: "定时任务",
              value: "2"
            }],
            val: '',
          }],
          cOpts: [{
            key: 'user_task_name',
            label: '模板名称',
            type: '',
            val: ''
          }]
        },
        tableData: [],
        pageParm: {
          "count": 0, //总条数
          "pageSize": 20, //每页条数
          "pageCount": 0, //总页数
          "startIndex": 1 //当前页数
        }
      }
    },
    computed: {
      ...mapGetters([
        'getUser',
        'getTenants'
      ])
    },
    methods: {

      getAuditTaskHttp () { //获取数据 请求

        let arg = {
          "conditions": {
            "user_task_name ": [],
            "user_name ": [],
            "task_run_type": []
          },
          "start_index": this.pageParm.startIndex,
          "page_count": this.pageParm.pageSize
        };
        let conditions = {};
        this.formInline.cOpts.map(item => {
          conditions[item.key] = [item.val]
        });
        if (conditions.task_run_type == null || conditions.task_run_type[0] == '') {conditions.task_run_type = null}
        arg.conditions = conditions;
        dao.getAuditTask(arg).then((response) => {
          let pageRes = response.body;
          this.tableData = pageRes.results;
          this.pageParm.count = parseInt(pageRes.count);
        }, (response) => {
          // error callback
          console.log(response)
        })

      },
      updateAuditTaskHttp: function () { //修改数据 请求

        let arg = {
          "user_task_id": this.form.user_task_id,
          "user_task_name": this.form.user_task_name,
          "user_defined_sql": this.form.user_defined_sql,
          "tenant_name": this.form.tenant_name,
          "user_queue_name": this.form.user_queue_name,
          "task_run_type": this.form.task_run_type,
          "task_timer_cron_exp": this.form.task_timer_cron_exp,
          "user_task_desc": this.form.user_task_desc,
          "update_time": new Date()
        };
        arg.task_run_type==1 ? arg.task_timer_cron_exp = "" : void 0;

        dao.updateAuditTask(arg).then((response) => {
          //success callback
          this.btnEditText = '提交';
          this.editLoading = false;
          let pageRes = response.body;
          if (pageRes.retCode == "200") {
            this.$message({
              message: '修改成功',
              type: 'success'
            });
            this.dialogFormVisible = false;
            this.getAuditTaskHttp();
          } else {
            this.$message.error('修改失败');
          }
        }).catch(res => {
          this.$message.error('请求服务器失败！');
        })

      },
      addAuditTaskHttp: function () { //创建数据 请求
        let arg = {
          "user_task_name": this.form.user_task_name,
          "user_defined_sql": this.form.user_defined_sql,
          "tenant_name": this.form.tenant_name,
          "user_queue_name": this.form.user_queue_name,
          "task_run_type": this.form.task_run_type,
          "task_timer_cron_exp": this.form.task_timer_cron_exp,
          "user_task_desc": this.form.user_task_desc,
          "create_time": new Date()
        };
        arg.task_run_type==1 ? arg.task_timer_cron_exp = "" : void 0;

        dao.addAuditTask(arg).then((response) => {
          //success callback
          this.btnEditText = '提交';
          this.editLoading = false;

          let pageRes = response.body;
          console.log(pageRes);
          if (pageRes.retCode == "200") {
            this.$message({
              message: '提交成功',
              type: 'success'
            });

            this.dialogFormVisible = false;
            this.getAuditTaskHttp();
          } else {
            this.$message.error('提交失败');
          }
        }).catch(res => {
          this.$message.error('请求服务器失败！');
        })

      },
      deleteAuditTaskHttp: function () { //删除数据请求

        //查询选中的稽核任务id
        let user_task_ids = [];
        let user_task_names = [];
        this.multipleSelection.map(item => {
          user_task_ids.push(item.user_task_id);
          user_task_names.push(item.user_task_name);
        });
        if (user_task_ids.length === 0) {
          alert("请至少选择一条记录！");
        } else {
          dao.deleteAuditTask({"user_task_ids": user_task_ids,"user_task_names":user_task_names}).then((response) => {
            if (!response.body || response.body.retCode != 200) {
              this.$message({
                type: 'error',
                message: '删除失败!'
              });
            } else {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              //刷新列表
              this.getAuditTaskHttp();
            }
          });
        }
      },
      validateName (rule, value, callback)  {
        if(this.dialogFormVisibleType == "update"){
          callback()
          return false
        }
        if (!value) {
          callback(new Error('请输入任务模板名称'));
        } else {
          dao.validateAuditTaskName({"audit_task_name": value}).then((response) => {
            if (response.body.retMsg != "1") {
              callback(new Error('任务名称重复'));
            }
            callback();
          })
        }
      },
      getQueueOptionsHttp(){ //获取队列 请求

        dao.getQueueListByUserId({}).then(res => {
          if (res.FX.err) return false;
          this.queueOptions = res.body.queueList || [{name: ''}]
        })

      },
      gotopage42: function () {

        let id = 123;
        this.$router.push({path: `/page42/${id}`, query: {plan: 'private'}});

      },
      editSubmit: function () {

        this.$refs.form.validate((valid) => {
          if (valid) {
            this.$confirm(this.editTips, this.formTitle, {
              type: 'info'
            }).then(() => {
              this.btnEditText = '提交中';
              this.editLoading = true;
              if (this.dialogFormVisibleType == "add") {
                this.addAuditTaskHttp();
              } else if (this.dialogFormVisibleType == "update") {
                this.updateAuditTaskHttp();
              } else {
                return false;
              }
            })
          } else {
            return false;
          }
        })

      },
      handleAdd: function () { //创建

        this.dialogFormVisibleType = "add";
        this.formTitle = "创建模板";
        this.editTips = "确定创建吗？";
        for (let i in this.form) {  //初始化表单
          this.form[i] = "";
        }
//        this.tenantNameList = this.getTenants || []; //获取租户
        this.form.user_id = this.getUser.user_id || ""; //获取user_id
        this.dialogFormVisible = true;

      },
      handleDelete: function () { //删除

        this.dialogFormVisibleType = "delete";
        this.$confirm('此操作将删除选中的任务模板, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteAuditTaskHttp();
        }).catch(() => { });

      },
      handleUpdate () { //修改

        if (this.multipleSelection[0].user_defined_sql) {
          this.multipleSelection[0].user_defined_sql = this.multipleSelection[0].user_defined_sql.toString() || "";
        }
        this.dialogFormVisibleType = "update";
        this.formTitle = "修改模板";
        this.editTips = "确定修改吗？";
        this.form = JSON.parse(JSON.stringify(this.multipleSelection[0])) || {};
//        this.getQueueOptionsHttp();
        this.dialogFormVisible = true;

      },
      handleChangeState: function (row) { // 启动停止事件判断

        let status = row.task_status
        let changeId = row.user_task_id || {}
        let ss_state = ''
        let fun=''

        if (row.task_run_type == 1) { ss_state = (row.task_status == "1") ? "停止" : "启动"; }
        else if (row.task_run_type == 2) { ss_state = (row.status == "0") ? "停止" : "启动"; }

        this.$confirm(`确定${ss_state}吗, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (row.task_run_type == 1) {
            if (row.task_status == "1") fun = "stopAuditTask"
            else fun = "startAuditTask"
          } else if (row.task_run_type == 2) {
            if (row.status == "0") fun = "disableableAuditTask"
            else fun = "enableAuditTask"

          }
          let arg = {"user_task_id": changeId};
          if(fun=='') return false;
          dao[fun](arg).then(res=>{
            if(res.FX.err) return false
            this.getAuditTaskHttp();
          })




        }).catch(() => { });

      },
      updateButStatus: function (val) { //通过条数判断 修改/删除 按钮是否可以点

        if (val.length == 1) {
          this.butStatus.modify = false;
          this.butStatus.deploy = false;
          this.butStatus.rm = false;
        } else if (val.length == 0) {
          this.butStatus.modify = true;
          this.butStatus.deploy = true;
          this.butStatus.rm = true;
        } else {
          this.butStatus.modify = true;
          this.butStatus.deploy = false;
          this.butStatus.rm = false;
        }

        for(let item of val){
          if (item.status == 0||item.task_status == 1||item.task_status == 4) {
            this.butStatus.rm = true
            break;
          }
        }

      },
      handleSelectionChange (val) { //选中条数

        this.multipleSelection = val;
        this.updateButStatus(val);

      },
      handleSizeChange (val) { //请求列表

        this.pageParm.pageSize = val;
        this.getAuditTaskHttp();

      },
      handleCurrentChange (val) { //页数跳转

        this.pageParm.startIndex = val;
        this.getAuditTaskHttp();

      },
      resetForm () { //重置表单
        this.$refs.form.resetFields();
        this.dialogFormVisible = false;
      }
    },
    mounted () {
      this.tenantNameList = this.getTenants || []; //获取租户
      this.getQueueOptionsHttp();
      this.getAuditTaskHttp();
    }
  }
</script>

<style scoped>
  .toolbar .el-form-item {
    margin-bottom: 10px;
  }

  .toolbar {
    background: #fff;
    padding: 10px 10px 0px 10px;
  }

</style>